<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Agent;
use App\Model\Cate;
use App\Model\Goods;
use App\Model\Supplier;
use Illuminate\Http\Request;

class GoodsController extends Controller
{
    public function __construct()
    {
        $this->middleware(['admin']);
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = Goods::where('status', '>', '-1');
        !empty($params['supplier_id']) && $model->where('supplier_id', $params['supplier_id']);
        !empty($params['agent_id']) && $model->where('agent_id', $params['agent_id']);
        !empty($params['cate_id']) && $model->where('cate_id', $params['cate_id']);
        !empty($params['name']) && $model->where('name', 'like', "%{$params['name']}%");
        isset($params['status']) && $params['status'] !== '' && $model->where('status', $params['status']);
        isset($params['is_home']) && $params['is_home'] !== '' && $model->where('is_home', $params['is_home']);
        $list = $model->orderBy('order_num', 'desc')->orderBy('id', 'desc')->paginate(15);
        return view('admin.goods.index', [
            'list' => $list,
            'cateNames' => Cate::pluck('name', 'id')->toArray(),
            'suppliers' => Supplier::pluck('name', 'id')->toArray(),
            'params' => $params,
            'agents' => Agent::pluck('name', 'id')->toArray(),
        ]);
    }

    public function getGoodsByAgentId(Request $request)
    {
        $list = Goods::select(['id', 'name'])->where('status', 1)->where('agent_id', $request->input('agent_id'))->get()->toArray();
        return response()->json($list);
    }
}